//
//  MAFuncListViewController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/8/3.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAFuncListViewController.h"
#import "MAFuncGroupModel.h"
#import "MAFuncItemModel.h"
#import "MAJiGouModel.h"
#import "MAFunctionCell.h"

@interface MAFuncListViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

/** groupModels */
@property(nonatomic,strong) NSMutableArray *groupModels;

/** groupModelsDict */
@property(nonatomic,strong) NSMutableDictionary *groupModelsDict;
/** groupDetailModels */
@property(nonatomic,strong) NSMutableArray *groupDetailModels;

/** realGroupModels */
@property(nonatomic,strong) NSMutableArray *realGroupModels;

@end

@implementation MAFuncListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    // 请求功能分组数据
    [self requestGroupModels:self.model.ID];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFuncData:) name:kMAChangeJiGouNotification object:nil];
}

- (void)setupTableView {
    
    self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.myTableView.tableFooterView = [UIView new];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)reloadFuncData:(NSNotification *)noti {
    DLog(@"%@",noti.userInfo[@"jigou_id"]);
    [self requestGroupModels:noti.userInfo[@"jigou_id"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestGroupModels:(NSString *)jigou_id {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [self.groupModels removeAllObjects];
    [self.groupDetailModels removeAllObjects];
    [self.realGroupModels removeAllObjects];
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",FUNCTION_GROUP_LIST,self.model.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.groupModels = [MAFuncGroupModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            if (self.groupModels.count) {
                for (MAFuncGroupModel *groupModel in self.groupModels) {
                    [self.groupModelsDict setObject:groupModel forKey:groupModel.groupid];
                }
            }
            
            // 请求对应功能分组的功能列表数据
            [self requestFuncListData:jigou_id];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        
    }];
}

- (void)requestFuncListData:(NSString *)jigou_id {
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",FUNCTION_BYORG_LIST,jigou_id];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.groupDetailModels = [MAFuncItemModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            
#warning TODO 需要处理功能的分组
            for (MAFuncItemModel *itemModel in self.groupDetailModels) {
                MAFuncGroupModel *groupModel = self.groupModelsDict[itemModel.groupid];
                [groupModel.items addObject:itemModel];
            }
            for (NSString *key in self.groupModelsDict) {
                NSInteger count = ((MAFuncGroupModel *)self.groupModelsDict[key]).items.count;
                if (count) {
                    [self.realGroupModels addObject:self.groupModelsDict[key]];
                }
            }
            
            [self.myTableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        
    }];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.realGroupModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    MAFuncGroupModel *model = self.realGroupModels[section];
    
    return model.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    MAFunctionCell *funcCell = [MAFunctionCell cellWithTableView:tableView];
    funcCell.groupModel = self.realGroupModels[section];
    return funcCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DLog(@"");
}

#pragma mark - getter & setter
- (NSMutableArray *)groupModels {
    if (_groupModels == nil) {
        _groupModels = [NSMutableArray array];
    }
    return _groupModels;
}
- (NSMutableArray *)groupDetailModels {
    if (_groupDetailModels == nil) {
        _groupDetailModels = [NSMutableArray array];
    }
    return _groupDetailModels;
}
- (NSMutableDictionary *)groupModelsDict {
    if (_groupModelsDict == nil) {
        _groupModelsDict = [NSMutableDictionary dictionary];
    }
    return _groupModelsDict;
}
- (NSMutableArray *)realGroupModels {
    if (_realGroupModels == nil) {
        _realGroupModels = [NSMutableArray array];
    }
    return _realGroupModels;
}
@end
